package vip.ifmm.lehouse.api.gateway.controller.file;

import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import vip.ifmm.lehouse.common.dto.ServerResponse;
import vip.ifmm.lehouse.common.enums.status.FileStatus;
import vip.ifmm.lehouse.common.model.Enclosure;
import vip.ifmm.lehouse.common.util.CodeUtil;
import vip.ifmm.lehouse.file.service.api.EnclosureService;
import vip.ifmm.lehouse.file.service.api.FileService;

import java.io.IOException;
import java.util.UUID;

/**
 * @author: mackyhuang
 * <p>email: mackyhuang@163.com <p>
 * <p>date: 2019/6/17 </p>
 */
@RestController
@RequestMapping("/file")
public class FileController {

    @Reference(owner = "mackyhuang")
    private FileService fileService;

    @Reference(owner = "mackyhuang")
    private EnclosureService enclosureService;

    /**
     * 对外暴露的文件上传接口
     * @param file springframework中的http文件传输类
    * @param module 文件在服务器中所属的模块
     * @return 文件上传结果
     */
    @PostMapping("/upload")
    public ServerResponse upload(MultipartFile file, String module){
        ServerResponse uploadResult = null;
        Enclosure enclosure = null;
        if (file == null || file.getSize() == 0){
            return ServerResponse.response(FileStatus.FILE_IS_EMPTY);
        }
        try {
            String uniqueId = CodeUtil.randomString(16);
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            uploadResult = fileService.upload(uniqueId, file.getBytes(), module, extension);
            //如果文件上传成功，才把信息存到数据库
            if (uploadResult.isSuccess()){
                enclosure = Enclosure.builder().enclosureName(file.getOriginalFilename())
                        .enclosurePath(uploadResult.getData().toString())
                        .enclosureSize((int) file.getSize())
                        .enclosureSuffix(extension).build();
                uploadResult = enclosureService.saveEnclosureInfo(enclosure);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return uploadResult;
    }
}
